package db

import (
	"errors"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)


var dbList map[string]*gorm.DB


// GetDb 获得 gorm.DB 实例
func GetDb(dbName string) (*gorm.DB, error) {

	// 方便开发调试
	if dbList == nil {
		InstDbList()
	}


	if _, ok := dbList[dbName]; ok {
		return dbList[dbName], nil
	}
	return nil,errors.New("找不到DB配置")
}

// InstDbList 初始化连接池
func InstDbList() (err error){


	dbList = make(map[string]*gorm.DB, 10)

	// 注册 users DB, 实际数据库名是 trygo_users
	err = registerDB("users", "test.lab.gclove.com", "23309", "trygo", "trygo", "trygo_users")
	if err != nil {
		return err
	}

	// 注册 billing DB, 实际数据库名是 trygo_users
	err = registerDB("billing", "test.lab.gclove.com", "23309", "trygo", "trygo", "trygo_billing")
	if err != nil {
		return err
	}

	return
}


// 注册 DB 连接池
func registerDB(name, host, port, user, pass, dbName string) error {

	// 这是 dsn 噢
	dsn := fmt.Sprintf(
		"%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		user,
		pass,
		host,
		port,
		dbName,
	)


	gormConfig := &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	}

	gormDB, err := gorm.Open(mysql.Open(dsn), gormConfig)

	if err == nil {
		dbList[name] = gormDB
	}

	return err
}

